package com.yourenbang.lingyun.transaction.web.service.impl.migrate;

import com.yourenbang.lingyun.constants.BizCodeMessages;
import com.yourenbang.lingyun.constants.Constant;
import com.yourenbang.lingyun.constants.enums.PlatNoEnums;
import com.yourenbang.lingyun.core.exception.BizRuntimeException;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.redis.CacheKey;
import com.yourenbang.lingyun.core.util.redis.RedisUtils;
import com.yourenbang.lingyun.domain.*;
import com.yourenbang.lingyun.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

@Slf4j
public abstract class AbstractMigrateService {

    /**
     * 获取凌云UserBaseId
     *
     * @param klksUserId 快收UserId
     */
    protected String getUserBaseId(UserBaseExtMapper userBaseExtMapper, String klksUserId, RedisUtils redis) {
        CacheKey key = new CacheKey(CacheKey.CacheKeyPrefix2.pay,
                StringUtils.join(new String[]{"migrate","getUserBaseId", klksUserId}, ":"));
        String userBaseId = redis.get(key);
        if(StringUtils.isNotBlank(userBaseId)){
            return userBaseId;
        }
        UserBaseExtExample baseExtExample = new UserBaseExtExample();
        baseExtExample.createCriteria()
                .andOtherUserIdEqualTo(klksUserId)
                .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode())
                .andIsDelEqualTo(Constant.NORMAL);
        List<UserBaseExt> userBaseExtList = userBaseExtMapper.selectByExample(baseExtExample);
        if (CollectionUtils.isEmpty(userBaseExtList)) {
            KLog.warn("[获取凌云UserBaseId],未获取到凌云UserBaseId,klksUserId:{}", klksUserId);
            throw new BizRuntimeException(BizCodeMessages.USER_NOT_EXISTS, "未获取到凌云UserBaseId");
        }
        userBaseId = userBaseExtList.get(0).getUserBaseId();
        redis.set(key, userBaseId, 60 * 60 * 24);
        return userBaseId;
    }

    /**
     * 获取资金账户id
     * @param fundAccountMapper
     * @param userBaseId
     * @return
     */
    protected int getFundAccountId(FundAccountMapper fundAccountMapper, String userBaseId,int accountType) {
        FundAccountExample fundAccountExample = new FundAccountExample();
        fundAccountExample.createCriteria().andUserBaseIdEqualTo(userBaseId)
                .andAccountTypeEqualTo(accountType)
                .andIsDelEqualTo(Constant.NORMAL);
        List<FundAccount> fundAccounts = fundAccountMapper.selectByExample(fundAccountExample);
        if (CollectionUtils.isEmpty(fundAccounts)) {
            KLog.error("[获取凌云FundAccount],未获取到凌云FundAccount,userBaseId:{}", userBaseId);
            throw new BizRuntimeException(BizCodeMessages.USER_NOT_EXISTS, "未获取到凌云资金账户");
        }
        return fundAccounts.get(0).getFundAccountId();
    }

    /**
     * 获取积分账户id
     * @param scoreAccountMapper
     * @param userBaseId
     * @return
     */
    protected int getScoreAccountId(ScoreAccountMapper scoreAccountMapper, String userBaseId,Integer accountType) {
        ScoreAccountExample scoreAccountExample = new ScoreAccountExample();
        scoreAccountExample.createCriteria().andUserBaseIdEqualTo(userBaseId)
                .andIsDelEqualTo(Constant.NORMAL)
                .andAccountTypeEqualTo(accountType);
        List<ScoreAccount> scoreAccounts = scoreAccountMapper.selectByExample(scoreAccountExample);
        if (CollectionUtils.isEmpty(scoreAccounts)) {
            KLog.error("[获取凌云FundAccount],未获取到凌云FundAccount,userBaseId:{}", userBaseId);
            throw new BizRuntimeException(BizCodeMessages.USER_NOT_EXISTS, "未获取到凌云积分账户");
        }
        return scoreAccounts.get(0).getScoreAccountId();
    }


    /**
     * 获取凌云UserBase
     *
     * @param klksUserId 快收UserId
     */
    protected UserBase getUserBase(UserBaseMapper userBaseMapper, UserBaseExtMapper userBaseExtMapper, String klksUserId, RedisUtils redis) {
        CacheKey key = new CacheKey(CacheKey.CacheKeyPrefix2.pay,
                StringUtils.join(new String[]{"migrate","getUserBase", klksUserId}, ":"));
        UserBase userBase = redis.get(key, UserBase.class);
        if(userBase != null){
            return userBase;
        }
        userBase = userBaseMapper.selectByPrimaryKey(getUserBaseId(userBaseExtMapper, klksUserId, redis));
        redis.set(key, userBase, 60 * 60 * 24);
        return userBase;
    }

    /**
     * 获取凌云Merchant20
     */
    protected Merchant20 getMerchant20(Merchant20Mapper merchant20Mapper, String userBaseId, Short channelId, RedisUtils redis) {
        CacheKey key = new CacheKey(CacheKey.CacheKeyPrefix2.pay,
                StringUtils.join(new String[]{"migrate","getMerchant20", userBaseId}, ":"));
        Merchant20 merchant20 = null;
        if (StringUtils.isNotBlank(userBaseId)
                && channelId != null) {
            merchant20 = redis.get(key, Merchant20.class);
            if(merchant20 != null){
                return merchant20;
            }
            Merchant20Example oldMerchant20Example = new Merchant20Example();
            oldMerchant20Example.createCriteria()
                    .andUserBaseIdEqualTo(userBaseId)
                    .andChannelIdEqualTo(channelId)
                    .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
            List<Merchant20> oldMerchant20List = merchant20Mapper.selectByExample(oldMerchant20Example);
            if (CollectionUtils.isNotEmpty(oldMerchant20List)) {
                merchant20 = oldMerchant20List.get(0);
                redis.set(key, merchant20, 60 * 60 * 24);
            }
        }
        return merchant20;
    }

//    protected String getPayType(String payType) {
//        if (StringUtils.isBlank(payType)) {
//            return null;
//        }
//        if (StringUtils.equals(payType, "wechat")) {
//            return PayTypeEnum.WECHAT.getCode();
//        } else if (StringUtils.equals(payType, "wechat_xcx")) {
//            return PayTypeEnum.WECHAT_PROGRAM.getCode();
//        } else if (StringUtils.equals(payType, "alipay")) {
//            return PayTypeEnum.ALIPAY.getCode();
//        } else if (StringUtils.equals(payType, "balance")) {
//            return PayTypeEnum.BALANCE.getCode();
//        } else if (StringUtils.equals(payType, "replace")) {
//            return PayTypeEnum.UNIONPAY.getCode();
//        } else if (StringUtils.equals(payType, "lakalasdk")) {
//            return PayTypeEnum.LAKALA_SDK_PAY.getCode();
//        } else if (StringUtils.equals(payType, "sips")) {
//            return PayTypeEnum.LAKALA_SIPS_MPOS.getCode();
//        } else if (StringUtils.equals(payType, "sips_qr")) {
//            return PayTypeEnum.LAKALA_SIPS_QR.getCode();
//        } else if (StringUtils.equals(payType, "point")) {
//            return PayTypeEnum.POINT.getCode();
//        } else if (StringUtils.equals(payType, "lakalaqrpay")) {
//            return PayTypeEnum.LAKALA_QR_PAY.getCode();
//        } else if (StringUtils.equals(payType, "lakala_dq")) {
//            return PayTypeEnum.LAKALA_EPOS_PAY.getCode();
//        } else if (StringUtils.equals(payType, "LAKALA_P35_PAY")) {
//            return PayTypeEnum.LAKALA_P35_PAY.getCode();
//        } else if (StringUtils.equals(payType, "LAKALA_P35")) {
//            return PayTypeEnum.LAKALA_SIPS_P35.getCode();
//        } else if (StringUtils.equals(payType, "sips_dq")) {
//            return PayTypeEnum.LAKALA_SIPS_EPOS.getCode();
//        } else if (StringUtils.equals(payType, "LINGGONGBAO")) {
//            return PayTypeEnum.LINGGONGBAO.getCode();
//        } else if (StringUtils.equals(payType, "HJTX")) {
//            return PayTypeEnum.HJTX.getCode();
//        } else if (StringUtils.equals(payType, "four_element_certify")) {
//            return PayTypeEnum.FOUR_ELEMENT_CERTIFY.getCode();
//        } else if (StringUtils.equals(payType, "raise_limit")) {
//            return PayTypeEnum.RAISE_LIMIT.getCode();
//        } else if (StringUtils.equals(payType, "lakala_faceidentify")) {
//            return PayTypeEnum.LAKALA_FACEIDENTIFY.getCode();
//        }
//        KLog.error("[格式化快收支付方式]不支持的支付方式,payType:{}", payType);
//        throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "不支持的支付方式");
//    }

    /**
     * 获取用户订单所在表
     */
    protected int getTransTableIndex(String userId) {
        int hashcode = userId.hashCode() % 100;
        return Math.abs(hashcode) + 1;
    }

    /**
     * 格式化 boolean字符串
     */
    protected String fmtBooleanStr(String booleanVal) {
        if (StringUtils.equalsIgnoreCase(booleanVal, "true")) {
            return "1";
        } else if (StringUtils.equalsIgnoreCase(booleanVal, "false")) {
            return "0";
        } else {
            return booleanVal;
        }
    }


}
